package com.coocaa.ops.admin.v1.upload.util;

import lombok.experimental.UtilityClass;
import org.apache.tomcat.util.http.fileupload.FileUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author bijiahao
 * @description
 * @date 2020/11/3 15:23
 */
@UtilityClass
public class DownloadUtil {

    public static void download(String httpUrl, String localPath) {
        HttpURLConnection conn = null;
        InputStream inputStream = null;
        BufferedInputStream bis = null;
        FileOutputStream out = null;
        try {
            File localFile = new File(localPath);
            FileUtils.forceMkdir(localFile.getParentFile());
            out = new FileOutputStream(localFile);
            // 建立链接
            URL url = new URL(httpUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            //连接指定的资源
            conn.connect();
            //获取网络输入流
            inputStream = conn.getInputStream();
            bis = new BufferedInputStream(inputStream);
            byte b[] = new byte[1024];
            int len = 0;
            while ((len = bis.read(b)) != -1) {
                out.write(b, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (bis != null) {
                    bis.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

    public static InputStream getInputStreamFromUrl(String httpUrl){
        try {
            // 建立链接
            URL url = new URL(httpUrl);
            HttpURLConnection  conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            //连接指定的资源
            conn.connect();
            //获取网络输入流
            InputStream inputStream = conn.getInputStream();
            return inputStream;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        String url = "http://art.51arttouch.com/upload/201908/15/7466F01E0FEE0174AC7574A2D8E343DC1507137899.jpg";
//        download(url, "/Users/bijiahao/test/cover999/ooo.jpg");
    }
}
